package org.goobs.applications;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.goobs.database.Database;
import org.goobs.mapping.City;
import org.goobs.mapping.IntercityRoad;
import org.goobs.mapping.RoadMap;
import org.goobs.utils.Util;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class RoadImporter {
	
	private static DocumentBuilder builder;
	
	private RoadMap map;
	
	public RoadImporter() throws SAXException{
		if(builder == null){
			try {
				builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			} catch (ParserConfigurationException e) {
				throw new SAXException("Could not create XML parser");
			}
		}
		System.out.print("Creating map...");
		this.map = new RoadMap(new Database("localhost", "java", "what?why42?", "europe"));
		System.out.println("Done");
	}

	public boolean importMap(String filepath) throws FileNotFoundException{
		File osm = new File(filepath);
		System.out.print("Parsing...");
		Document doc;
		try {
			doc = builder.parse(osm);
		} catch (SAXException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
		System.out.println("Done");
		System.out.println("Adding to database...");
		this.map.parse(doc, true);
		return true;
	}
	
	public void generateCities(){
		System.out.println("extracting cities...");
		Set <City> cities = this.map.extractCityMap();
		System.out.println("-----\n------\n------\n");
		for(City c : cities){
			System.out.println(c);
			for(IntercityRoad r : c.getRoads()){
				System.out.println("\t" + r);
			}
		}
		map.saveCityMap(cities, new File("/home/gabor/workspace/Peter/map.txt"));
	}
	
	public static void main(String argv[]) {
//		if(argv.length != 1){
//			System.err.println("Invalid argument count: " + argv.length);
//			System.exit(1);
//		}
		String filename = argv[0];
		if(Util.compareFilenames(filename, "../data/osm_europe/europe-5240.osm") < 0){
			System.out.println("already imported: " + filename);
			System.exit(0);
		}
		System.out.println("IMPORTING " + filename);
		try {
			RoadImporter importer = new RoadImporter();
			importer.importMap(filename);
//			importer.generateCities();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
}
